package pl.edu.uj.tcs.blef.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;


public class ServerConnectionHandler extends Thread {
	private Socket socket;
	private ServerListener listener;
	private BufferedReader inputStream;
	
	public ServerConnectionHandler(ServerListener listener, Socket socket) throws IOException{
		this.listener = listener;
		this.socket = socket;
		this.inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		start();
	}
	
	@Override
	public void run(){
		String inputLine = new String();
		try {
			while(true){		
				inputLine = inputStream.readLine();
				if(inputLine == null){
					this.listener.decrementConnections();
					System.out.println("Connection broke...");
					return;
				}
				
				System.out.println("Try to parse message: " + inputLine);
				ServerRequestHeadquarters.parse(inputLine, socket);
			} 
		} catch (IOException e) {
			this.listener.decrementConnections();
			System.out.println("Connection broke...");
			return;
		}
	}
}
